package com.piece.module.spider.executor.shape;

import com.piece.core.framework.util.string.StringUtil;
import com.piece.module.spider.context.SpiderContext;
import com.piece.module.spider.support.SpiderNode;
import com.piece.module.spider.util.ExpressionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;

/**
 * 函数执行器
 */
@Slf4j
@Component
public class FunctionExecutor implements ShapeExecutor {

	public static final String FUNCTION = "function";

	@Override
	public void execute(SpiderNode node, SpiderContext context, Map<String,Object> variables) {
		List<Map<String, String>> functions = node.getListJsonValue(FUNCTION);
		for (Map<String, String> item : functions) {
			String function = item.get(FUNCTION);
			if(StringUtil.isNotEmpty(function)){
				try {
					ExpressionUtil.execute(function, variables);
				} catch (Exception e) {
					log.error("执行函数{}失败,异常信息:{}", function, e);
					ExceptionUtils.wrapAndThrow(e);
				}
			}
		}
	}

	@Override
	public String supportShape() {
		return "function";
	}
}
